const tableSelect = {
  data() {
    return {
      multipleSelection: [],
    }
  },
  methods: {
    /**
      * 全选/全取消
      */
    onSelectAll(rows, data) {
      if (rows.length) {
        rows.forEach((item) => {
          if (!this.multipleSelection.find((child) => child.id === item.id)) {
            this.multipleSelection.push(item);
          }
        });
      } else {
        data.forEach((item) => {
          this.onSelectionChange(rows, item);
        });
      }
    },
    /**
      * 选择表格某一行
      */
    onSelectionChange(rows, val) {
      const isHas = this.multipleSelection.findIndex((item) => item.id === val.id);
      if (isHas > -1) {
        this.multipleSelection.splice(isHas, 1);
      } else {
        this.multipleSelection.push(val);
      }
    },
    /**
      * 初始化表格选择
      */
    handleSelect(data) {
      const selectData = [];
      data.forEach((item) => {
        if (this.multipleSelection.find((child) => child.id === item.id)) selectData.push(item);
      });
      if (selectData.length) {
        this.$nextTick(() => {
          selectData.forEach((row) => {
            this.$refs.table.toggleRowSelection(row);
          });
        });
      }
    }
  }
}

export default tableSelect
